﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace Zatify.Domain.Helpers
{
    public static class Helper
    {
        public static Image ScaleImage(byte[] imgBytes, int maxWidth, int maxHeight)
        {
            var ic = new System.Drawing.ImageConverter();
            var img = (System.Drawing.Image)ic.ConvertFrom(imgBytes);

            //Image img;
            //using (var m = new System.IO.MemoryStream(imgBytes))
            //{
            //    img = Image.FromStream(m);
            //}

            return ScaleImage(img, maxWidth, maxHeight);
        }

        public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
        {
            var ratioX = (double)maxWidth / image.Width;
            var ratioY = (double)maxHeight / image.Height;
            var ratio = Math.Min(ratioX, ratioY);

            var newWidth = (int)(image.Width * ratio);
            var newHeight = (int)(image.Height * ratio);

            var newImage = new Bitmap(newWidth, newHeight);
            Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
            return newImage;
        }

        public static byte[] ImageToByteArray(Image image)
        {
            var ic = new System.Drawing.ImageConverter();

            return (byte[])ic.ConvertTo(image, typeof(byte[]));
        }
    }
}
